﻿//-----------------------------------------------------------------------
// <copyright file="GDICanvasRenderer.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace TileTool.Base.Render
{
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using TileTool.Common.Math;
    using TileTool.Render;
    using TileTool.Render.Settings;
    using TileTool.Settings;

    /// <summary>
    /// Implementation of the canvas renderer that uses GDI+.
    /// </summary>
    public class GDICanvasRenderer : CanvasRendererBase, ICanvasRenderer
    {
        #region Fields - Private

        /// <summary>
        /// Graphics object to use during draw calls.
        /// </summary>
        private Graphics graphics;

        /// <summary>
        /// Control that owns this renderer.
        /// </summary>
        private System.Windows.Forms.Control ownerControl;

        /// <summary>
        /// Matrix to use to flip our coordinate system so we can work
        /// in Cartesian coordinates.
        /// </summary>
        private Matrix flipMatrix = new Matrix(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f);

        #endregion

        #region Methods - Constructor

        /// <summary>
        /// Constructor for the canvas renderer.
        /// </summary>
        /// <param name="owner">Control that owns this renderer.</param>
        public GDICanvasRenderer(System.Windows.Forms.Control owner)
        {
            this.ownerControl = owner;
        }

        #endregion

        #region Methods - Public - Rendering

        /// <summary>
        /// Called to begin a render.
        /// </summary>
        /// <param name="g">Graphics object to use for the render.</param>
        public void BeginRender(Graphics g)
        {
            this.graphics = g;

            // Always call the changed functions since we are starting a render,
            // so we need to push our current states to the graphics object.
            this.TransformChanged();
            this.AntiAliasChanged();
        }

        /// <summary>
        /// Called when rendering is complete.
        /// </summary>
        public void EndRender()
        {
            this.graphics = null;
        }

        /// <summary>
        /// Clear the canvas with the passed color.
        /// </summary>
        /// <param name="color">Color to clear the canvas with.</param>
        public void Clear(ColorRGBA color)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            this.graphics.Clear(Color.FromArgb(color.a, color.r, color.g, color.b));
        }

        /// <summary>
        /// Draw a line from point a to b with the passed color and line width.
        /// </summary>
        /// <param name="a">Start point.</param>
        /// <param name="b">End point.</param>
        /// <param name="color">Line color.</param>
        /// <param name="width">Line width.</param>
        public void DrawLine(Vector2D a, Vector2D b, ColorRGBA color, float width)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            using (Pen pen = new Pen(Color.FromArgb(color.a, color.r, color.g, color.b)))
            {
                pen.Width = width;

                this.graphics.DrawLine(pen, a.x, a.y, b.x, b.y);
            }
        }

        /// <summary>
        /// Draw a line rectangle.
        /// </summary>
        /// <param name="pos">Position of the rectangle.</param>
        /// <param name="size">Size of the rectangle to draw.</param>
        /// <param name="color">Color of the rectangle.</param>
        /// <param name="width">Width of the lines that make up the rectangle.</param>
        public void DrawLineRect(Vector2D pos, Size2D size, ColorRGBA color, float width)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            using (Pen pen = new Pen(Color.FromArgb(color.a, color.r, color.g, color.b)))
            {
                pen.Width = width;
                this.graphics.DrawRectangle(pen, pos.x, pos.y, size.Width, size.Height);
            }
        }

        /// <summary>
        /// Draw a filled rectangle.
        /// </summary>
        /// <param name="pos">Position of the rectangle.</param>
        /// <param name="size">Size of the rectangle to draw.</param>
        /// <param name="color">Color of the rectangle.</param>
        public void DrawFilledRect(Vector2D pos, Size2D size, ColorRGBA color)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            using (Brush brush = new SolidBrush(Color.FromArgb(color.a, color.r, color.g, color.b)))
            {
                using (Pen pen = new Pen(brush))
                {
                    this.graphics.FillRectangle(brush, pos.x, pos.y, size.Width, size.Height);
                }
            }
        }

        /// <summary>
        /// Draw a line ellipse.
        /// </summary>
        /// <param name="pos">Center position of the ellipse.</param>
        /// <param name="size">Size of the ellipse.</param>
        /// <param name="color">Color of the ellipse.</param>
        /// <param name="width">Width of the lines that make up the ellipse.</param>
        public void DrawLineEllipse(Vector2D pos, Size2D size, ColorRGBA color, float width)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            using (Pen pen = new Pen(Color.FromArgb(color.a, color.r, color.g, color.b)))
            {
                pen.Width = width;
                this.graphics.DrawEllipse(pen, pos.x - (size.Width * 0.5f), pos.y - (size.Height * 0.5f), size.Width, size.Height);
            }
        }

        /// <summary>
        /// Draw a filled ellipse.
        /// </summary>
        /// <param name="pos">Center position of the ellipse.</param>
        /// <param name="size">Size of the ellipse.</param>
        /// <param name="color">Color of the ellipse.</param>
        public void DrawFilledEllipse(Vector2D pos, Size2D size, ColorRGBA color)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            using (Brush brush = new SolidBrush(Color.FromArgb(color.a, color.r, color.g, color.b)))
            {
                using (Pen pen = new Pen(brush))
                {
                    this.graphics.FillEllipse(brush, pos.x - (size.Width * 0.5f), pos.y - (size.Height * 0.5f), size.Width, size.Height);
                }
            }
        }

        /// <summary>
        /// Draw a line triangle made up of the passed points.
        /// </summary>
        /// <param name="p0">Point 0.</param>
        /// <param name="p1">Point 1.</param>
        /// <param name="p2">Point 2.</param>
        /// <param name="color">Color of the triangle.</param>
        public void DrawLineTriangle(Vector2D p0, Vector2D p1, Vector2D p2, ColorRGBA color)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            PointF[] points = new PointF[6];

            points[0] = new PointF(p0.x, p0.y);
            points[1] = new PointF(p1.x, p1.y);
            points[2] = new PointF(p1.x, p1.y);
            points[3] = new PointF(p2.x, p2.y);
            points[4] = new PointF(p2.x, p2.y);
            points[5] = new PointF(p0.x, p0.y);

            using (Pen pen = new Pen(Color.FromArgb(color.a, color.r, color.g, color.b)))
            {
                this.graphics.DrawPolygon(pen, points);
            }
        }

        /// <summary>
        /// Draw a filled triangle made up of the passed points.
        /// </summary>
        /// <param name="p0">Point 0.</param>
        /// <param name="p1">Point 1.</param>
        /// <param name="p2">Point 2.</param>
        /// <param name="color">Color of the triangle.</param>
        public void DrawFilledTriangle(Vector2D p0, Vector2D p1, Vector2D p2, ColorRGBA color)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            PointF[] points = new PointF[6];

            points[0] = new PointF(p0.x, p0.y);
            points[1] = new PointF(p1.x, p1.y);
            points[2] = new PointF(p1.x, p1.y);
            points[3] = new PointF(p2.x, p2.y);
            points[4] = new PointF(p2.x, p2.y);
            points[5] = new PointF(p0.x, p0.y);

            using (Brush brush = new SolidBrush(Color.FromArgb(color.a, color.r, color.g, color.b)))
            {
                using (Pen pen = new Pen(brush))
                {
                    this.graphics.FillPolygon(brush, points);
                }
            }
        }

        #endregion

        #region Methods - Public - Render utility functions

        /// <summary>
        /// Draw a grid using the color values in RenderSettings.
        /// </summary>
        /// <param name="camera">Camera to use as a reference in drawing.</param>
        /// <param name="width">Width of each grid cell.</param>
        /// <param name="height">Height of each grid cell.</param>
        public void DrawGrid(ICamera camera, int width, int height)
        {
            Debug.Assert(this.graphics != null, "Graphics object must be non-null.");

            if (width <= 0.0f)
            {
                throw new ArgumentOutOfRangeException("width must be greater than 0.0f");
            }

            if (height <= 0.0f)
            {
                throw new ArgumentOutOfRangeException("height must be greater than 0.0f");
            }

            bool antiAliasEnabled = AntiAlias;
            RenderSettings settings = SettingsSystem.Get<RenderSettings>();

            this.PushState();
            this.AntiAlias = false;
            this.DrawGridLines(settings, camera, width, height);
            this.PopState();
        }

        #endregion

        #region Methods - Protected

        /// <summary>
        /// Called when the render transform changes.
        /// </summary>
        protected override void TransformChanged()
        {
            base.TransformChanged();

            Matrix2D transform = Transform;
            Matrix transformMatrix = new Matrix(
                transform.mat0,
                transform.mat1,
                transform.mat2,
                transform.mat3,
                transform.mat4,
                transform.mat5);

            this.graphics.ResetTransform();
            this.graphics.MultiplyTransform(transformMatrix, MatrixOrder.Append);
            this.graphics.MultiplyTransform(this.flipMatrix, MatrixOrder.Append);

            // Put the origin of the coordinate system in the center of the window.
            Rectangle clientRect = this.ownerControl.ClientRectangle;

            this.graphics.TranslateTransform(clientRect.Width * 0.5f, clientRect.Height * 0.5f, MatrixOrder.Append);
        }

        /// <summary>
        /// Called when the state of anti-aliasing changed.
        /// </summary>
        protected override void AntiAliasChanged()
        {
            base.AntiAliasChanged();

            if (this.AntiAlias)
            {
                this.graphics.SmoothingMode = SmoothingMode.HighQuality;
            }
            else
            {
                this.graphics.SmoothingMode = SmoothingMode.Default;
            }
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Draw a grid with the passed sizes.
        /// </summary>
        /// <param name="settings">Render settings object to use.</param>
        /// <param name="camera">Camera that is viewing the grid.</param>
        /// <param name="width">Width of the X grid.</param>
        /// <param name="height">Height of the Y grid.</param>
        private void DrawGridLines(RenderSettings settings, ICamera camera, int width, int height)
        {
            Vector2D end = new Vector2D();
            Vector2D start = new Vector2D();
            Rect2D cameraRect = camera.Rect;
            ColorRGBA drawColor = settings.GridLineColor;
            int startXPos = (int)(((int)(cameraRect.Left / width) * width) - width);
            int endXPos = (int)cameraRect.Right;
            bool drawMajorAxisX = false;

            for (int x = startXPos; x <= endXPos; x += width)
            {
                if (x == 0)
                {
                    drawMajorAxisX = true;
                    continue;
                }

                start.x = (float)x;
                start.y = cameraRect.Bottom;

                end.x = start.x;
                end.y = cameraRect.Top;

                this.DrawLine(start, end, drawColor, 1.0f);
            }

            bool drawMajorAxisY = false;
            int startYPos = (int)(((int)(cameraRect.Bottom / height) * height) - height);
            int endYPos = (int)cameraRect.Top;

            for (int y = startYPos; y <= endYPos; y += height)
            {
                if (y == 0)
                {
                    drawMajorAxisY = true;
                    continue;
                }

                start.x = cameraRect.Left;
                start.y = (float)y;

                end.x = cameraRect.Right;
                end.y = start.y;

                this.DrawLine(start, end, drawColor, 1.0f);
            }

            if (drawMajorAxisX)
            {
                start.x = 0.0f;
                start.y = cameraRect.Top;

                end.x = start.x;
                end.y = cameraRect.Bottom;

                this.DrawLine(start, end, settings.GridAxisColor, 1.0f);
            }

            if (drawMajorAxisY)
            {
                start.x = cameraRect.Left;
                start.y = 0.0f;

                end.x = cameraRect.Right;
                end.y = start.y;

                this.DrawLine(start, end, settings.GridAxisColor, 1.0f);
            }
        }

        #endregion
    }
}
